package com.leyou.second.scheduled;

import com.leyou.client.item.ItemClient;
import com.leyou.item.pojo.SeckillGoods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时获取服务Token的任务类
 */
@Component
@Slf4j
public class SkuSeckillScheduler {

    @Autowired
    private ItemClient itemClient;
    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 10000L; //24小时


    /**
     * 定时获取服务token
     * 需求：每隔24小时获取1次
     */
    @Scheduled(fixedRate = 600000L)
    public void findAllSeckill() {
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps("Seckill");
        if (!redisTemplate.hasKey("Seckill")) {
            log.info("加载秒杀商品数据到redis中");
            List<SeckillGoods> seckillGoods = itemClient.findAllSeckill();
            seckillGoods.forEach(seckillGood -> {
                Long skuId = seckillGood.getSkuId();
                boundHashOps.put(skuId.toString(), seckillGood.getSkillStock().toString());
            });
        }

    }


}
